package serialization;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

import io.protostuff.LinkedBuffer;
import io.protostuff.ProtostuffIOUtil;
import io.protostuff.Schema;
import io.protostuff.runtime.RuntimeSchema;

public class ProtostuffSerialize implements ISerialize {

	private static final Map<Class, Schema> map = new ConcurrentHashMap<Class, Schema>();

	private static final Schema schema = RuntimeSchema.getSchema(SerializeObjectWrapper.class);
	
	
	public byte[] serialize(Object obj) {
//		Schema sc = getSchema(obj.getClass());
		SerializeObjectWrapper wrapper = new SerializeObjectWrapper(obj);
		LinkedBuffer buffer = LinkedBuffer.allocate(4096);
		byte[] protostuff = null;
		try {
			protostuff = ProtostuffIOUtil.toByteArray(wrapper, schema, buffer);
		} catch (Exception ex) {
			ex.printStackTrace();
		} finally {
			buffer.clear();
		}
		return protostuff;
	}

	public <T> T unSerialize(byte[] byts, Class<T> t) {
		SerializeObjectWrapper wrapper = new SerializeObjectWrapper();
//		Schema sc = getSchema(t);
		ProtostuffIOUtil.mergeFrom(byts, wrapper, schema);
		return (T) wrapper.getObject();
	}

	private Schema getSchema(Class cls) {
		Schema sc = map.get(cls);
		if (sc == null) {
			sc = RuntimeSchema.getSchema(cls);
			map.put(cls, sc);
		}
		return sc;
	}

}
